<?php
/**
 * Created by PhpStorm.
 * User: Inhere
 * Date: 2015/2/6
 * Use :
 * File: MysqlDriver.php
 */
namespace ulue\core\db\mysql\driver;

use ulue\core\db\base\pdo\PdoDriver;
use ulue\core\db\helper\PdoDsnHelper;

class MysqlDriver extends PdoDriver
{
    protected $name = 'mysql';

    public function __construct(\PDO $connect = null, $options = array())
    {
        $options = $this->parseOptions($options);

        // Finalize initialisation
        parent::__construct($connect, $options);

    }

    /**
     * 解析选项， 主要是使用 dsn 时 提取部分信息
     * @param  array  $options
     * dsn = 'mysql:host=localhost;port=3306;dbname=db_test;charset=utf8'
     * @return array
     */
    protected function parseOptions(array $options)
    {
        // 拆解 dsn 信息
        if ( !empty($options['dsn']) ) {
            $dsn = str_replace(' ', '', $options['dsn']);
            unset($options['dsn']);

            $data = explode(':', $dsn, 2);
            $options['driver'] = $data[0];

            $arr = explode(';', $data[1]);

            foreach ($arr as $value) {
                $nodes = $arr = explode('=', $value);

                if ($nodes[0] == 'dbname') {
                    $nodes[0] = 'database';
                }

                $options[$nodes[0]] = $nodes[1];
            }
        }

        $defaultOptions = array(
            'driver'        => 'mysql',
            'host'          => 'localhost',
            'port'          => '3306',
            'database'      => '',
            'username'      => '',
            'password'      => '',
            'charset'       => 'UTF8',
            'driverOptions' => array(),
            'tblPrefix'     => '',
        );

        $options = array_merge($defaultOptions, array_filter($options));

        // 重新组织dsn信息
        $options['dsn'] = PdoDsnHelper::getDsn($this->name, $options);

        unset($config,$pos);

        return $options;
    }


}// end class MysqlDriver